//
//  OSSpinLockDemo2.m
//  JKThreadTest
//
//  Created by 王冲 on 2018/10/24.
//  Copyright © 2018年 JK科技有限公司. All rights reserved.
//

#import "OSSpinLockDemo2.h"

/**
 OSSpinLock 不再安全是因为会出现优先级反转问题，当有多条线程的时候，优先级比较高的线程会优先占用lock(锁)，优先级相对较低的线程就无法加锁，只有等优先级高的线程先执行完才可以进行加锁和解锁。
 */
#import <libkern/OSAtomic.h>

@interface OSSpinLockDemo2 ()


@end

@implementation OSSpinLockDemo2

static OSSpinLock moneyLock_;
+ (void)initialize
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        moneyLock_ = 0;
    });
}

-(void)__buyTicket{
    
    //    static NSString *str = nil;
    //    static dispatch_once_t onceToken;
    //    dispatch_once(&onceToken, ^{
    //        str = [NSString stringWithFormat:@"123"];
    //    });
    
    static OSSpinLock ticketLock = OS_SPINLOCK_INIT;
    
    OSSpinLockLock(&ticketLock);
    
    [super __buyTicket];
    
    OSSpinLockUnlock(&ticketLock);
    
}

-(void)__drawMoney{
    
    OSSpinLockLock(&moneyLock_);
    
    [super __drawMoney];
    
    OSSpinLockUnlock(&moneyLock_);
}

-(void)__saveMoney{
    
    OSSpinLockLock(&moneyLock_);
    
    [super __saveMoney];
    
    OSSpinLockUnlock(&moneyLock_);
}

@end
